//
//  ViewController.m
//  WaterMask
//
//  Created by txj on 2018/6/4.
//  Copyright © 2018年 杭州灵析网络科技有限公司. All rights reserved.
//

#import "ViewController.h"
#import "ImageUtils.h"
#import "TZImagePickerController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <Photos/Photos.h>

#define kWeakSelf __weak __typeof(self)weakSelf = self;

@interface ViewController ()<TZImagePickerControllerDelegate>
{
    NSInteger _currentImageIndex;
}
@property (weak, nonatomic) IBOutlet UILabel *lbMasker1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UITextView *lbMarker;
@property (strong, nonatomic) NSArray<UIImage *> *selPhotos;
@property (strong, nonatomic) NSArray<PHAsset *> *selAssets;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)btnPreTapped:(id)sender {
    if (_selPhotos.count>0) {
        UIImage *img=[_selPhotos objectAtIndex:0];
        _imageView.image = [ImageUtils getWaterMarkImage:img andTitle:_lbMarker.text andMarkColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
    }
}

- (IBAction)btnSaveTapped:(id)sender {
    [SVProgressHUD showProgress:_currentImageIndex status:@"图片处理中"];
    if (_selPhotos.count>0) {
        if (_lbMarker.text.length>0) {
            _currentImageIndex=0;
            [self saveNext];
            _imageView.image=[ImageUtils getWaterMarkImage:[_selPhotos lastObject] andTitle:_lbMarker.text andMarkColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"请输入水印文字"];
        }
    }
    else{
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
    }
}

-(void)saveNext
{
    if (_currentImageIndex<_selPhotos.count) {
        PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
        option.resizeMode = PHImageRequestOptionsResizeModeFast;
        option.networkAccessAllowed=NO;
        [[PHImageManager defaultManager]
         requestImageForAsset:[self.selAssets objectAtIndex:_currentImageIndex]
         targetSize:PHImageManagerMaximumSize
         contentMode:PHImageContentModeAspectFit
         options:option
         resultHandler:^(UIImage *resultImage, NSDictionary *info) {
            /** 必须做判断，要不然将走多次完成的completion的block */
            if ([[info objectForKey:PHImageResultIsDegradedKey] boolValue]) {
                return;
            }
            UIImage *img=[ImageUtils getWaterMarkImage:resultImage andTitle:self.lbMarker.text andMarkColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
            UIImageWriteToSavedPhotosAlbum(img, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
        }];
    }
    else{
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%ld张水印添加成功,已经保存到相册",(long)_currentImageIndex]];
    }
}

-(void) savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
    if (error) {
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%ld张图片保存失败",(long)_currentImageIndex]];
    }
    else {
        _currentImageIndex++;
    }
    [self saveNext];
}

- (IBAction)btnImageSelectTapped:(id)sender {
    self.selPhotos=nil;
    kWeakSelf
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:30 delegate:self];
    picker.isSelectOriginalPhoto=YES;
    [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count>0) {
            weakSelf.selPhotos=photos;
            weakSelf.selAssets=assets;
            weakSelf.imageView.image=[photos lastObject];
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"总共选了%lu张图片，请点击保存图片生成带水印的图片",(unsigned long)photos.count]];
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"没有选中的图片"];
        }
    }];
    [self presentViewController:picker animated:YES completion:nil];
}

/**
 通过资源获取图片的数据
 
 @param mAsset 资源文件
 @param imageBlock 图片数据回传
 */
- (void)fetchImageWithAsset:(PHAsset*)mAsset imageBlock:(void(^)(NSData*))imageBlock {
    
    [[PHImageManager defaultManager] requestImageForAsset:mAsset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage *resultImage, NSDictionary *info) {
        
        if ([[info valueForKey:@"PHImageResultIsDegradedKey"]integerValue] == 0){
            // 这里获取的 resultImage 的确是原图
            // 所以需要将 resultImage 转成 NSData 类型的
            // 方案一
            NSData* imageData = UIImagePNGRepresentation(resultImage);
            { // 方案二
                imageData = UIImageJPEGRepresentation(resultImage, 1.0);
            }
            // 通过 imageBlock 返回
            if (imageBlock) {
                imageBlock(imageData);
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
